package com.market2.utils.converter.impl;

import com.market2.dto.OperationDto;
import com.market2.model.Contrat;
import com.market2.model.Investisseur;
import com.market2.model.Negociation;
import com.market2.model.Operation;
import com.market2.utils.converter.Converter;

public class OperationConverter extends Converter
{
	@SuppressWarnings("unchecked")
	public OperationDto convertTo(Object source)
	{
		if(source == null || !(source instanceof Operation)) {
			return null;
		}
		
		OperationDto result = new OperationDto();
		Operation operation = (Operation) source;
		
		result.setNumero(operation.getNumero());
		result.setStatus(operation.getStatus());
		result.setDate(operation.getDate());
		
		if(operation.getContrat() != null) {
			result.setContrat(operation.getContrat().getNumero());
		}
		
		if(operation.getNegociation() != null) {
			result.setNegociation(operation.getNegociation().getNumero());
		}
		
		if(operation.getAcheteur() != null) {
			result.setAcheteur(operation.getAcheteur().getLogin());
		}
		
		if(operation.getVendeur() != null) {
			result.setVendeur(operation.getVendeur().getLogin());
		}
		
		return result;
	}

	@SuppressWarnings("unchecked")
	public Operation convertFrom(Object source)
	{
		if(source == null || !(source instanceof OperationDto)) {
			return null;
		}
		
		OperationDto operation = (OperationDto) source;
		Operation result = new Operation();
		
		result.setNumero(operation.getNumero());
		result.setStatus(operation.getStatus());
		result.setDate(operation.getDate());
		
		if(operation.getAcheteur() != null) {
			Investisseur acheteur = getEntityManager().find(Investisseur.class, operation.getAcheteur());
			result.setAcheteur(acheteur);
		}

		if(operation.getVendeur() != null) {
			Investisseur vendeur = getEntityManager().find(Investisseur.class, operation.getVendeur());
			result.setVendeur(vendeur);
		}

		if(operation.getContrat() != null) {
			Contrat contrat = getEntityManager().find(Contrat.class, operation.getContrat());
			result.setContrat(contrat);
		}
		
		if(operation.getNegociation() != null) {
			Negociation negociation = getEntityManager().find(Negociation.class, operation.getNegociation());
			result.setNegociation(negociation);
		}
		
		return result;
	}
}
